package com.springboot.frame.oauth.server.utils;

import com.alibaba.fastjson.JSON;
import com.springboot.frame.oauth.server.exception.Oauth2Exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j(topic = "ResponseUtils对象JSON响应")
public class ResponseUtils {


    public static void renderJson(HttpServletResponse response, Oauth2Exception e) {
        renderJson(response, e.getResultCode() );
    }

    public static void renderJson(HttpServletResponse response, ResultCode resultCode) {
        renderJson(response, resultCode,null);
    }

    /**
     * 往 response 写出 json
     *
     * @param response 响应
     * @param resultCode 状态
     * @param data     返回数据
     */
    public static void renderJson( HttpServletResponse response, ResultCode resultCode, Object data) {
        try {
            response.setStatus(HttpStatus.OK.value());
            //  将JSON转为String的时候，忽略null值的时候转成的String存在错误
            RestResult result = null != data ? new RestResult(resultCode, data) : new RestResult(resultCode);
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            log.error("Response写出JSON异常，", ex);
        }
    }

    /**
     * 往 response 写出 json
     *
     * @param response 响应
     * @param result 返回数据
     */
    public static void renderSuccessJson(HttpServletRequest request, HttpServletResponse response, RestResult result) {
        try {
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            log.error("Response写出JSON异常，", ex);
        }
    }
}
